package com.repro.baselib.lib_base.network.interceptors

import android.text.TextUtils
import com.future.retronet.logger.LogUtil
import com.repro.baselib.lib_base.constant.RetroNetConstant
import com.repro.lib_base.constant.RetroNetKey
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Interceptor
import okhttp3.Response

/**
 * 多host切换
 * 原理通过onRequest请求头里面添加type识别当前需要设置的host
 */
class BaseHostInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val originRequest = chain.request()//获取请求
        val originURL = originRequest.url
        LogUtil.e("\"原来的：${originURL.host}   ${originURL.port}\"")
        //检查头部是否包含hostTypes
        val hostType = originRequest.header(RetroNetKey.mRetroHostTypeKEY)
        if (!hostType.isNullOrBlank()){
            val newRequestHost = hostType?.toHttpUrlOrNull()
            LogUtil.e("\"新的：${newRequestHost?.host}   ${newRequestHost?.port}\"")
            //这里判别请求里面域名和hostType是否一致.如果不一致则需要替换host
            val newBuilder = originRequest.newBuilder()
            if (!TextUtils.isEmpty(hostType) && originURL.host != newRequestHost?.host) {
                newBuilder.removeHeader(RetroNetConstant.baseHost)
                newRequestHost?.let {
                    //构建新的host配置
                    val newHttpConfig = originURL.newBuilder()
                        .scheme(it.scheme)
                        .host(it.host)
                        .port(it.port)
                        .build()
                    val newHostBuilder = newBuilder.url(newHttpConfig).build()
                    return chain.proceed(newHostBuilder)
                }
            }
        }
        return chain.proceed(originRequest)
    }
}